package system.config;

import lombok.Getter;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Date;
import java.util.TimeZone;

@Getter
@Configuration
public class DateTimeConfig {

    public static final String ISO8601MILLI = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
    public static final String ISO8601 = "yyyy-MM-dd'T'HH:mm:ssXXX";

    private String dateFormat;
    private String timeZone;
    private DateTimeFormatter formatter;

    public DateTimeConfig(
            @Value("${spring.jackson.date-format}") String dateFormat,
            @Value("${spring.jackson.time-zone}") String timeZone
    ) {
        this.dateFormat = dateFormat;
        this.timeZone = timeZone;
        this.formatter = DateTimeFormatter.ofPattern(dateFormat).withZone(TimeZone.getTimeZone(timeZone).toZoneId());
    }

    public DateFormat newDateFormat() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
        return simpleDateFormat;
    }

    public String formatDate(Date date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
        return simpleDateFormat.format(date);
    }

    @SneakyThrows
    public Date parseDate(String date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
        return simpleDateFormat.parse(date);
    }

    public String formatDateTime(TemporalAccessor date) {
        return formatter.format(date);
    }

    @SneakyThrows
    public LocalDateTime parseDateTime(String date) {
        return LocalDateTime.parse(date, formatter);
    }

}
